package com.zengqingfa.juc.n3;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zengqingfa
 * @className TwoPhaseTermination
 * @description
 * @create 2021/6/8 22:44
 */
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination {

    Thread monitor;

    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread currentThread = Thread.currentThread();
                if (currentThread.isInterrupted()) {
                    log.debug("料理后事。。");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("执行监控记录。。");
                } catch (InterruptedException e) {
                    //打断sleep后，出现异常后，会清除标记
                    e.printStackTrace();
                    //重新设置打断标记
                    currentThread.interrupt();
                }
            }

        }, "监控线程");
        monitor.start();
    }

    public void stop() {
        monitor.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination t = new TwoPhaseTermination();
        t.start();
        Thread.sleep(3500);
        log.debug("stop");
        t.stop();
    }
}